import chess
import chess.engine
import chess.pgn


outputfile=open("intermediatedata/lichess.csv","w")


#engine = chess.engine.SimpleEngine.popen_uci("stockfish-11-win/Windows/stockfish_20011801_x64")


outputfile.write("Game, event,white, whiteelo, black, blackelo, timecontrol, result,  turn, move, eval, clock \n" )

pgn=open("rawdata/lichess_db_standard_rated_2017-04.pgn")

flag=1

gamecounter=0
    
while flag==1:
        
    gamenode=chess.pgn.read_game(pgn)

    if gamenode is None: 
        flag=0
        continue

    gamecounter+=1

    print(str(gamecounter), gamenode.headers["Event"], gamenode.headers["White"],gamenode.headers["Black"])
    #board = gamenode.board()
    #moves=gamenode.mainline_moves()

    counter=0

    white=gamenode.headers["White"]
    black=gamenode.headers["Black"]
    whiteelo=gamenode.headers["WhiteElo"]
    blackelo=gamenode.headers["BlackElo"]
    event=gamenode.headers["Event"]
    timecontrol=gamenode.headers["TimeControl"]
    result=gamenode.headers["Result"]
    
    for gamemove in gamenode.mainline_moves():
        counter+=1
        
        #print(gamemove)
        
        gamenode=gamenode.variation(gamemove)
        #print(gamenode.clock())
        
        
        move=gamenode.san()
        eval=gamenode.eval()
        clock=gamenode.clock()
        
        outputstring=str(gamecounter)+","+str(event)+","+white+","+str(whiteelo)+","+black+","+str(blackelo)+","+str(timecontrol)+","+str(result)+","+str(counter)+","+move+","+str(eval)+","+str(clock)+"\n"
        
        if str(eval)!="None":
            outputfile.write(outputstring)
    
outputfile.close()

